/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.rpc.simright;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.common.json.utils.JsonUtils;
import com.comac.ins.isfd.rpc.simright.bo.SimrightResponseBo;
import com.comac.ins.isfd.rpc.simright.constants.SimrightConstants;
import com.comac.ins.isfd.rpc.simright.constants.enums.SimrightResponseCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SimrightRestTemplateUtils {


    @Autowired
    private RestTemplate simrightRestTemplate;

    /**
     * 发送 post 请求
     * 默认：服务器接受 json 类型数据，客户端接受 json 类型数据
     */
    public SimrightResponseBo post(String url, Object requestBody) {
        Map<String, String> httpHeaderMap = new HashMap<>();
        httpHeaderMap.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        httpHeaderMap.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
        return sendRequest(url, HttpMethod.POST, requestBody, httpHeaderMap);
    }

    /**
     * 发送 get 请求
     * 默认：客户端接受 json 类型数据
     */
    public SimrightResponseBo get(String url) {
        // 设置默认请求头
        Map<String, String> httpHeaderMap = new HashMap<>();
        httpHeaderMap.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        return sendRequest(url, HttpMethod.GET, null, httpHeaderMap);
    }

    /**
     * 发送请求
     *
     * @param method 请求方式
     */
    public SimrightResponseBo sendRequest(String url, HttpMethod method, Object requestBody, Map<String, String> httpHeaderMap) {
        HttpHeaders headers = new HttpHeaders();
        // 设置请求头
        httpHeaderMap.keySet().forEach(key -> {
            headers.add(key, httpHeaderMap.get(key));
        });
        log.info("调用第三方数巧服务项目接口地址：{} , 入参：{}", url, JsonUtils.toJsonString(requestBody));
        HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);

        // 使用 String 接收响应
        ResponseEntity<String> response;
        try {
            response = simrightRestTemplate.exchange(url, method, entity, String.class);
        } catch (RestClientException e) {
            log.error("调用第三方数巧服务项目接口异常", e);
            throw new BaseException("调用第三方数巧服务项目接口异常: " + e.getMessage());
        }

        if (!response.getStatusCode().is2xxSuccessful()) {
            log.error("调用第三方数巧服务项目接口失败，HTTP状态码：{}", response.getStatusCode());
            throw new BaseException("调用第三方数巧服务项目接口失败，HTTP状态码：" + response.getStatusCode());
        }

        String responseBody = response.getBody();
        if (StringUtils.isBlank(responseBody)) {
            throw new BaseException("调用第三方数巧服务项目接口失败，返回体为空");
        }

        JSONObject body;
        try {
            body = JSONUtil.parseObj(responseBody);
        } catch (Exception e) {
            log.error("解析数巧接口返回体失败, body: {}", responseBody, e);
            throw new BaseException("解析数巧接口返回体失败: " + e.getMessage());
        }

        Integer code = body.getInt(SimrightConstants.CODE);
        if (!SimrightResponseCodeEnum.SUCCESS.getValue().equals(code)) {
            log.error("调用第三方数巧服务项目接口失败,response error code is {}", code);
            throw new BaseException("调用第三方数巧服务项目接口失败，返回的code不正确");
        }

        String data = body.getStr(SimrightConstants.DATA);
        String msg = body.getStr(SimrightConstants.MSG);

        SimrightResponseBo simrightResponseBo = new SimrightResponseBo();
        simrightResponseBo.setCode(code);
        simrightResponseBo.setMsg(msg);
        simrightResponseBo.setData(data);
        log.info("调用第三方数巧服务项目接口成功，返回参数data：{}",
            data == null ? "" : JsonUtils.toJsonString(data));
        return simrightResponseBo;
    }

}
